import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import classNames from 'classnames'
import PropTypes from 'prop-types'
import { PAGES } from '@/constants/tabPages'
import './index.scss'

@connect(state => ({ phoneInfo: state.mobile.mobile }))
class XtNavBar extends Taro.PureComponent {
  static options = {
    addGlobalClass: true
  }
  static externalClasses = ['custom-class']
  static defaultProps = {
    title: ''
  }
  static propTypes = {
    title: PropTypes.string
  }
  state = {
    statusBarHeight: 20,
    navBarHeight: 44,
    autoShowBack: false, // 是否显示返回按钮
    backIcon: 'at-icon-chevron-left'
  }
  mobileInfo = Taro.getStorageSync('MOBILE_INFO')
  componentDidMount() {
    // console.log(this.props.phoneInfo, 'ssss')
    const { phoneInfo } = this.props
    const navBarHeight = phoneInfo.statusBarHeight + this.state.navBarHeight
    this.setState(
      {
        statusBarHeight: phoneInfo.statusBarHeight,
        navBarHeight
      },
      () => {
        if (phoneInfo.navBarHeight !== navBarHeight) {
          this.props.dispatch({ type: 'PUT_MOBILE_INFO', payload: { navBarHeight } })
        }
      }
    )

    // 自定义导航是否显示返回按钮
    const pages = Taro.getCurrentPages()
    // console.log(pages, '路径')
    if (pages.length > 1) {
      this.setState({
        autoShowBack: true,
        backIcon: 'at-icon-chevron-left'
      })
    } else {
      if (pages[0] && PAGES.indexOf(pages[0].route) === -1) {
        this.setState({
          autoShowBack: true,
          backIcon: 'at-icon-home'
        })
      }
    }
  }

  // 自定义导航返回按钮点击
  goBack() {
    const { backIcon } = this.state
    backIcon === 'at-icon-chevron-left' ? Taro.navigateBack() : Taro.switchTab({ url: '/pages/home/index' })
  }

  render() {
    const { title } = this.props
    const { autoShowBack, statusBarHeight = 20, backIcon } = this.state
    const headerStl = {}
    if (this.mobileInfo && this.mobileInfo.statusBarHeight) {
      headerStl.paddingTop = this.mobileInfo.statusBarHeight + 'px'
    } else {
      headerStl.paddingTop = statusBarHeight + 'px'
    }

    const leftBar = (
      <View className='xt-navBar-left' onClick={this.goBack.bind(this)}>
        <Text className={classNames('at-icon xt-navbar-icon', backIcon)}></Text>
      </View>
    )
    const center = <View className='xt-navBar-name'>{title}</View>

    return (
      <View className='xt-header' style={headerStl}>
        <View className={classNames('xt-navBar', 'custom-class')} style={headerStl}>
          <View className='xt-header-content'>
            {autoShowBack && leftBar}
            {title ? center : this.props.children}
          </View>
        </View>
      </View>
    )
  }
}
export default XtNavBar
